<?php
include "header.php";
if($_COOKIE['userrole']!="1")
{
    die("admin need");
}
?>

<div class="container-fluid">
    <div class="col-sm-12  col-md-12  main">
        <h1 class="page-header">用户
            <button id="btn_cancelCreateUser" type="button" class="btn btn-lg btn-warning pull-right" onclick="cancelCreateUser()" style="display: none">取消</button>
            <button id="btn_finish" type="button" class="btn btn-lg btn-success pull-right" onclick="finishCreateUser()" style="display: none">保存</button>
            <button id="btn_modify" type="button" class="btn btn-lg btn-success pull-right" onclick="finishModifyUser()" style="display: none">修改</button>
            <button id="btn_create" type="button" class="btn btn-lg btn-success pull-right" onclick="showCreateUserDiv()">创建</button>

        </h1>

        <div style="padding: 40px 100px 10px;display: none" id="div_createUser">
            <form class=" horizontal" role="form" id="aboveform">

                <div class="form-group form-group-fix" >
                    <label for="input_name" class="col-sm-2 form-label">用户名</label>
                    <div class="col-sm-10">
                    		<input id="input_name" type="text" class="form-control" placeholder="请输入用户名，用于登陆和显示" onblur="checkWidgetEcho(this.id,'user','username',this.value,current_modifyuser_id,'用户名')">
                    </div>
                    
                </div>
				
				<div class="form-group form-group-fix" >
                    <label for="input_companyname" class="col-sm-2 control-label">顾问公司名称</label>
                    <div class="col-sm-10">
                    		<input id="input_companyname" type="text" class="form-control" placeholder="请输入顾问公司名称" onblur="">
                    	</div>
                </div>
				
				<div class="form-group form-group-fix">
                    <label for="input_address" class="col-sm-2 control-label">顾问公司地址</label>
                    <div class="col-sm-10">
                    		<input id="input_address" type="text" class="form-control" placeholder="请输入顾问公司所在地址" onblur="">
                    </div>
                    
                </div>
                
                <div class="form-group form-group-fix">
                    <label for="input_tel" class="col-sm-2 control-label">顾问公司电话</label>
                    <div class="col-sm-10">
                    		<input id="input_tel" type="text" class="form-control" placeholder="请输入顾问公司的联系电话" onblur="">
                    </div>
                    
                </div>


                <div class="form-group form-group-fix">
                    <label for="select_role" class="col-sm-2 control-label">属于角色</label>
					<div class="col-sm-10">
                    		<select id="select_role" class="cls_select2 form-control" name="select_role">

                    		</select>
                    	</div>

                </div>


				<div class="form-group form-group-fix">
                    <label for="input_emailname" class="col-sm-2 control-label">姓名1</label>
					<div class="col-sm-10">
                    		<input id="input_emailname" type="text" name="emailname"   class="form-control" placeholder="请输入姓名1，一般为顾问的姓名" >
                    	</div>
                </div>

                <div class="form-group form-group-fix">
                    <label for="input_email" class="col-sm-2 control-label">电子邮箱1</label>
					<div class="col-sm-10">
                    		<input id="input_email" type="text" name="email"   class="form-control" placeholder="请输入姓名1对应电子邮箱" onblur="checkWidgetEcho(this.id,'user','email',this.value,current_modifyuser_id,'姓名1对应电子邮箱')">
                    	</div>
                </div>
                
                <div class="form-group form-group-fix">
                    <label for="input_email2name" class="col-sm-2 control-label">姓名2</label>
					<div class="col-sm-10">
                    		<input id="input_email2name" type="text" name="email2name"   class="form-control" placeholder="请输入姓名2，一般为顾问上司的姓名" >
                    	</div>
                </div>

                <div class="form-group form-group-fix">
                    <label for="input_email2" class="col-sm-2 control-label">电子邮箱2</label>
					<div class="col-sm-10">
                    		<input id="input_email2" type="text" name="email2"   class="form-control" placeholder="请输入姓名2对应电子邮箱" onblur="">
                    	</div>
                </div>
                
                <div class="form-group form-group-fix">
                    <label for="input_price188a" class="col-sm-2 control-label">188A方案价格</label>
                    <div class="col-sm-10">
                    		<input id="input_price188a" type="number" class="form-control" placeholder="请输入188A的价格" onblur="">
                    	</div>
                </div>
                
                <div class="form-group form-group-fix">
                    <label for="input_price188b" class="col-sm-2 control-label">188B方案价格</label>
                    <div class="col-sm-10">
                    		<input id="input_price188b" type="number" class="form-control" placeholder="请输入188B的价格" onblur="">
                    	</div>
                </div>
                
                <div class="form-group form-group-fix">
                    <label for="input_price188c" class="col-sm-2 control-label">188C方案价格</label>
                    <div class="col-sm-10">
                    		<input id="input_price188c" type="number" class="form-control" placeholder="请输入188C的价格" onblur="">
                    	</div>
                </div>
                
                <div class="form-group form-group-fix" >
                    <label for="input_price188c" class="col-sm-2 control-label">132方案价格</label>
                    <div class="col-sm-10">
                    		<input id="input_price132" type="number" class="form-control" placeholder="请输入132的价格" onblur="">
                    	</div>
                </div>
                
                
				 <div class="form-group form-group-fix" >
                    <label for="input_companylog" class="col-sm-2 control-label">公司logo</label>
                    <div class="col-sm-10" id='div_fileupload'>
                    		<input id="fileUpload" type="file" class="form-control">
                    	</div>
                </div>

            </form>
        </div>

        <div class="table-responsive">
            <table class="table table-striped " id="userTable" >

            </table>
        </div>
    </div>
</div>
</div>

<script>
    var tableurl="api.php?method=getUsersTable";
    var $table = $('#userTable');
    $(function(){
        $table.bootstrapTable({
            //url: "merchantTable.json",
            url:tableurl,
            dataType: "json",
            pagination: true, //分页
            singleSelect: false,
            search: true, //显示搜索框
            pageSize:10,
            columns: [
                {
                    title: 'ID',
                    field: 'id',
                    align: 'left',
                    valign: 'middle'
                },
                {
                    title: '用户名',
                    field: 'name',
                    align: 'left',
                    valign: 'middle'
                },
                {
                    title: '电子邮箱',
                    field: 'email',
                    align: 'left',
                    valign: 'middle'
                },
                {
                    title: '所属角色',
                    field: 'rolename',
                    align: 'left',
                    valign: 'middle'
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'left',
                    formatter:function(value,row,index){
                        s=e=e2=d="";

                        if(row.name!="admin")
                        {
                            e='<a href="#" mce_href="#" onclick="editU(\''+ row.id + '\',\''+row.name+'\',\''+row.email+'\',\''+row.email2+'\',\''+row.emailname+'\',\''+row.email2name+'\',\''+row.tel+'\',\''+row.companyname+'\',\''+row.address+'\',\''+row.price188a+'\',\''+row.price188b+'\',\''+row.price188c+'\',\''+row.price132+'\',\''+row.logopath+'\',\''+row.roleid+'\')">编辑 </a>'
                            e2='<a href="#" mce_href="#" onclick="resetUPwd(\''+ row.id + '\')">重置密码 </a>'
                            d = '<a href="#" mce_href="#" onclick="delU(\''+ row.id +'\')">删除</a> ';
                        }


                        return s+e+e2+d;
                    }
                }
            ]
        });

        $('#aboveform').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                email: {
                    validators: {
                        notEmpty: {
                            message: '邮箱地址不能为空'
                        },
                        emailAddress: {
                            message: '邮箱地址格式有误'
                        }
                    }
                }
            }
        });
    })



    $('.cls_select2').select2({width:"100%"});
    $('.cls_select2_50').select2({width:"50%"});
    $('.cls_select2_mt').select2({width:"100%",multiple: true});

    getRoles();


    function getRoles()
    {


        $.ajax({
            url:'api.php?method=getRoles',
            type:'POST', //GET
            async:true,    //或false,是否异步
            timeout:5000,    //超时时间
            dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend:function(xhr){
                console.log(xhr)
                console.log('发送前')
            },
            success:function(data,textStatus,jqXHR){
                //alert(data.name);
                for(o in data)
                {
                    if(data[o].id==undefined)continue;
                    $("#select_role").append("<option value='" + data[o].id + "'>&nbsp;" + data[o].name + "</option>");

                }



            },
            error:function(xhr,textStatus){
                console.log('错误')
                console.log(xhr)
                console.log(textStatus)
            },
            complete:function(){
                console.log('结束')
            }
        });




    }


    current_modifyuser_id=0;
    function editU(id,name,email,email2,emailname,email2name,tel,companyname,address,price188a,price188b,price188c,price132,logopath,rid)
    {
        //leak floor_info, ,roles
        current_modifyuser_id = id;
        $("#input_name").val(name);
        $("#input_email").val(email);
        $("#input_email2").val(email2);
        $("#input_emailname").val(emailname);
        $("#input_email2name").val(email2name);
        $("#input_tel").val(tel);
        $("#input_companyname").val(companyname);
        $("#input_address").val(address);
        $("#input_price188a").val(price188a);
        $("#input_price188b").val(price188b);
        $("#input_price188c").val(price188c);
        $("#input_price132").val(price132);
        $("#select_role").val(rid).trigger("change");
        //logopath
        
//      $('#fileUpload').fileinput('refresh', {
//      	 showPreview :true,
//			initialPreview:"<img src='"+logopath+"' class='file-preview-image' />"
// 		 });
		$("#div_fileupload").empty();
		var ele='<input id="fileUpload" type="file" class="form-control">';
		$("#div_fileupload").append(ele);                          
		initFileInput("fileUpload", "api.php?method=companylogoupload",logopath+"?"+Math.random());
        showModifyUserDiv();
    }



    function delU(uid)
    {
        bootbox.prompt("<font color='red'>确定要删除此用户吗？</font>（此操作不可撤销！如需删除请在下方输入“确认删除”）",function (result) {
            if(result=="确认删除")
            {
                $.ajax({
                    url:'api.php?method=delUser',
                    type:'POST', //GET
                    async:true,    //或false,是否异步
                    data:{
                        id:uid
                    },
                    timeout:5000,    //超时时间
                    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                    beforeSend:function(xhr){
                        console.log(xhr)
                        console.log('发送前')
                    },
                    success:function(data,textStatus,jqXHR){
                        //alert(data.name);
                        if(data.return_code=="0")
                        {

                            bootbox.alert("删除成功",function () {

                                $("#userTable").bootstrapTable('refresh',{'url':tableurl});
                            });
                        }
                        else
                        {
                            bootbox.alert("删除失败");
                        }



                    },
                    error:function(xhr,textStatus){
                        console.log('错误')
                        console.log(xhr)
                        console.log(textStatus)
                    },
                    complete:function(){
                        console.log('结束')
                    }
                });
            }
        })
    }

    function showCreateUserDiv()
    {
        $("#div_createUser").show();
        $("#btn_cancelCreateUser").show();
        $("#btn_finish").show();
        $("#btn_create").hide();
        current_modifyuser_id=0;
        $(".table-responsive").hide();
    }

    function cancelCreateUser()
    {
        $("#div_createUser").hide();
        $("#btn_cancelCreateUser").hide();
        $("#btn_finish").hide();
        $("#btn_modify").hide();
        $("#btn_create").show();

        $("#input_name").val("");
        $("#input_email").val("");
        $("#input_email2").val("");
        $("#input_emailname").val("");
        $("#input_email2name").val("");
        $("#input_tel").val("");
        $("#input_companyname").val("");
        $("#input_address").val("");
        $("#input_price188a").val("");
        $("#input_price188b").val("");
        $("#input_price188c").val("");
        $("#input_price132").val("");

        $("#select_role").val("").trigger("change");
        $(".table-responsive").show();
        
        $("#fileUpload").fileinput('clear'); 
    }

    function showModifyUserDiv()
    {
        $("#div_createUser").show();
        $("#btn_cancelCreateUser").show();
        $("#btn_modify").show();
        $("#btn_create").hide();
        $(".table-responsive").hide();



    }

    function checkUserInput()
    {

        $('#aboveform').data('bootstrapValidator').validate();
        if(!$('#aboveform').data('bootstrapValidator').isValid()){
            return ;
        }
        name = $("#input_name").val();


        email = $("#input_email").val();
        email2 = $("#input_email2").val();
        emailname = $("#input_emailname").val();
        email2name = $("#input_email2name").val();
        price188a = $("#input_price188a").val();
        price188b = $("#input_price188b").val();
        price188c = $("#input_price188c").val();
        price132 = $("#input_price132").val();
        
        companyname = $("#input_companyname").val();
      
        
        tel=$("#input_tel").val();
        address=$("#input_address").val();
        

        role=$("#select_role").val();



        if(name=="")
        {
            bootbox.alert("用户名称不能为空");
            return false;
        }
        else if(email == "")
        {
            bootbox.alert("电子邮箱1不能为空",function () {

            })
            return false;
        }
        else if(email2 == "")
        {
            bootbox.alert("电子邮箱2不能为空",function () {

            })
            return false;
        }
        else if(emailname == "")
        {
            bootbox.alert("姓名1不能为空",function () {

            })
            return false;
        }
        else if(email2name == "")
        {
            bootbox.alert("姓名2不能为空",function () {

            })
            return false;
        }
        else if(tel == "")
        {
            bootbox.alert("电话不能为空",function () {

            })
            return false;
        }
        else if(address == "")
        {
            bootbox.alert("地址不能为空",function () {

            })
            return false;
        }
        
        else if(price188a == "")
        {
            bootbox.alert("188A方案价格不能为空",function () {

            })
            return false;
        }
        else if(price188b == "")
        {
            bootbox.alert("188B方案价格不能为空",function () {

            })
            return false;
        }
        else if(price188c == "")
        {
            bootbox.alert("188B方案价格不能为空",function () {

            })
            return false;
        }
        
        else if(price132 == ""|| role==null)
        {
            bootbox.alert("132方案价格不能为空",function () {

            })
            return false;
        }
        else if(companyname == ""|| role==null)
        {
            bootbox.alert("公司名不能为空",function () {

            })
            return false;
        }
        //alert(role);
        return true;
    }

    function finishModifyUser()
    {
        bcheck=checkUserInput();
        if(!bcheck)return;
        bootbox.confirm("确定修改此用户的信息吗？",function (result) {
			$("#fileUpload").fileinput("upload");
            if(result)
                $.ajax({
                    url:'api.php?method=modifyUser',
                    type:'POST', //GET
                    async:true,    //或false,是否异步
                    data:{
                        id:current_modifyuser_id,
                        name:name,
                        email:email,
                        email2:email2,
                        emailname:emailname,
                        email2name:email2name,
                        price188a:price188a,
                        price188b:price188b,
                        price188c:price188c,
                        price132:price132,
                        companyname:companyname,
                        address:address,
                        tel:tel,
                        role_id:role,
                    },
                    timeout:5000,    //超时时间
                    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                    beforeSend:function(xhr){
                        console.log(xhr)
                        console.log('发送前')
                    },
                    success:function(data,textStatus,jqXHR){
                        //alert(data.name);
                        if(data.return_code=="0")
                        {
                            bootbox.alert("修改成功",function () {
                                cancelCreateUser();
                                $("#userTable").bootstrapTable('refresh',{'url':tableurl});
                            });
                        }
                        else
                        {
                            alert(data.return_msg);
                        }



                    },
                    error:function(xhr,textStatus){
                        console.log('错误')
                        console.log(xhr)
                        console.log(textStatus)
                    },
                    complete:function(){
                        console.log('结束')
                    }
                });
        })

    }

    function finishCreateUser()
    {
        bcheck=checkUserInput();
        if(!bcheck)return;

        //return;
		$("#fileUpload").fileinput("upload");
        $.ajax({
            url:'api.php?method=addUser',
            type:'POST', //GET
            async:true,    //或false,是否异步
            data:{
                name:name,
                email:email,
                email2:email2,
                emailname:emailname,
                email2name:email2name,
                price188a:price188a,
                price188b:price188b,
                price188c:price188c,
                price132:price132,
                companyname:companyname,
                address:address,
                tel:tel,
                role_id:role,

            },
            timeout:5000,    //超时时间
            dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend:function(xhr){
                console.log(xhr)
                console.log('发送前')
            },
            success:function(data,textStatus,jqXHR){
                //alert(data.name);
                if(data.return_code=="0")
                {
                	
                    bootbox.alert("创建成功",function () {
                        cancelCreateUser();
                        $("#userTable").bootstrapTable('refresh',{'url':tableurl});
                    });
                }
                else
                {
                    if(data.return_code=="-3")
                    {
                        bootbox.alert("用户名或电子邮箱重复，请重新输入！");
                        return;
                    }

                }



            },
            error:function(xhr,textStatus){
                console.log('错误')
                console.log(xhr)
                console.log(textStatus)
            },
            complete:function(){
                console.log('结束')
            }
        });

    }


	function initFileInput(ctrlName, uploadUrl,logopath) {
	 var control = $('#' + ctrlName);
	 control.fileinput({
	  language: 'zh', //设置语言
	  uploadUrl: uploadUrl, //上传的地址 (该方法需返回JSON字符串)
	  uploadAsync: false,
	  allowedFileExtensions: ['jpg', 'gif', 'bmp','png','jpeg'],//接收的文件后缀
	  overwriteInitial:true,
	  showRemove:false,
	  showUpload: false, //是否显示上传按钮
	  showCaption: false,//是否显示标题
	  showClose:false,
	  autoReplace:true,
	  maxImageWidth: 500,//图片的最大宽度

      maxImageHeight: 500,//图片的最大高度
	  maxFileSize:400,
	  elCaptionText:'hello',
	  dropZoneTitle:'请点击下方选择按钮上传图片，也可以拖拽LOGO图片到这里上传，大小限制为400kb，长宽请勿超过500像素！',
	  layoutTemplates:{
	  	actionDelete:'',
	  	actionUpload:''
	  },
	  browseClass: "btn btn-primary", //按钮样式
	  allowedPreviewTypes : [ 'image' ],
	  initialPreviewAsData: true,
	  initialPreview: [   
                //预览图片的设置  
               logopath],
	  uploadExtraData:function(){
            return {
            	'username':$("#input_name").val(),
            	'role_id':$("#select_role").val()
            };
        }
	 })
//	 .on('filebatchselected', function (event, data, id, index) {
//	 	alert(JSON.stringify(event));
//	 	if($("#input_name").val()=="")
//	 	{
//	 		alert("请输入用户名后再上传公司logo");
//	 		$(this).fileinput('clear'); 
//	 		return;
//	 	}
//	 	else if($(this).fileinput("getFilesCount")>=2)
//	 	{
//	 		
//	 		alert("只允许上传一张图片")
//	 	}
//	 	else	
//	  	$(this).fileinput("upload");
//	 })
	 .on("fileuploaded", function (event, data) {
	  if (data.response) {
	   
	  //通过 data.response.Json对象属性 获得返回数据
	  errors = data.response.ErrorList;
	  }
	 })
	 }
	 
	//上传JS初始化
	 $(function () {
	 initFileInput("fileUpload", "api.php?method=companylogoupload","");
	 });
	//获取上传文件弹窗关闭动作
	$("#fileUpload").change(function () { /*alert("上传文件弹窗已关闭")*/ })
	

</script>
</body>
</html>
